package 案例;

import java.io.*;
import java.util.Scanner;

//查找文件(文章内容和查找内容相匹配)
public class Demo_3 {
    public static void main(String[] args) {
        //输入地址
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入要查询的地址：");
        String findPath = scanner.next();
        System.out.println("输入查询的内容：");
        String word = scanner.next();

        //检查输入的合法性
        File findDir = new File(findPath);
        if(!findDir.isDirectory()){
            System.out.println("地址有误");
            return;
        }

        //开始查找
        searchFile(findDir,word);
    }

    private static void searchFile(File findDir, String word) {
        File[] files = findDir.listFiles();
        for(File file: files){
            if(file.isFile()){
                searchInFile(file,word);
            }else if(file.isDirectory()){
                searchFile(file,word);
            }else {
                System.out.println("没有找到");
            }
        }

    }

    private static void searchInFile(File file, String word) {
        try(InputStream inputStream = new FileInputStream(file)){
            StringBuffer stringBuffer =new StringBuffer();
            while(true){
                byte[] buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if(n==-1){
                    break;
                }
                String s = new String(buffer,0,n);
                stringBuffer.append(s);
            }
            if(stringBuffer.indexOf(word)==-1){ 
                return;
            }
            System.out.println("找到了"+word+"，地址为："+file.getAbsoluteFile());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
